<?php
use com\gdl\newagk\interfaces\PlaformServiceIf;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\newagk\dataobject\platform\PlaformInfoResultDTO;
use com\gdl\newagk\dataobject\platform\PlaformInviteCodeAddRequestDTO;
use com\gdl\newagk\dataobject\platform\PlaformInviteCodeResultDTO;
use com\gdl\newagk\dataobject\platform\PlaformDTO;

class api_PlaformService extends api_Abstract implements PlaformServiceIf
{


    /**
     * 取得相关平台
     * @param type $platformType
     * @param type $name
     * @return ResultDO
     */
    public function getPlaform($platformType, $name,$userid = 0,$level)
    {
        if ($level) {
            $data = [];
            $ids = [];
            $condition = array();
            $result = new ResultDO();
			$result->message = 0;
            $userid = $userid ? gdl_lib_BaseUtils::getStr($userid, 'int') : 0;
			$offset = $platformType ? gdl_lib_BaseUtils::getStr($platformType, 'int') : 0;
			$num = $num ? gdl_lib_BaseUtils::getStr($num, 'int') :10;
			
			#分页
			if($offset=='0') $offset=1;
			$rows = $num;
			$limit = ($offset - 1) * $rows . "," . $rows;
			

            $leftJoin = array(
                'agk_user_company as uc' => 'agk_platform.id=uc.platformId'
            );
            $condition['uc.userId'] = $userid;
            $condition['agk_platform.status'] = 1;
			$condition['uc.isdelete'] = 0;
            $items = 'agk_platform.id,agk_platform.parentid,agk_platform.`reals`,uc.id as indetity_id,uc.status,uc.isdelete,uc.vface';
            //$groupBy = 'group by agk_platform.id';
			$groupBy = 'order by agk_platform.id desc limit '.$limit;
            try {
                $modelPlaform = new model_newagk_platform();
                $res = $modelPlaform->select($condition, $items, $groupBy, '', $leftJoin)->items;
				$resCount = $modelPlaform->select($condition, $items, '', '', $leftJoin)->items;
				$result->message = count($resCount) ? intval(count($resCount)) : 0;
				
                //进行平台顶级读取处理 
                $servPlaform = new service_platform();
                
                foreach ($res as $k => $r) {
                    //if ($r['parentid'] != 0) {
                      //  $id = $servPlaform->getTopPlaformIdbyId($r['parentid']);
                        //if (!in_array($id['id'], $ids)) {
                          //  $data[] = ['id' => $id['id'], 'name' => $id['real'] , 'identity_id' => $r['indetity_id']];
                        //}
                    //} else {
                        if(!in_array($r['id'], $ids)){
                            $data[] = ['id' => $r['id'], 'name' => $r['reals'] , 'identity_id' => $r['indetity_id'],'status'=>$r['status'],'isdelete'=>$r['isdelete'],'vface'=>$r['vface']];
                        }
                    //}
                    $ids[] = $r['id'];
                } 
                if ($res) {
                    $result->data = $data;
                    $result->code = 200;
                } else {
                    $result->code = 200;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
        } else {
            $condition = array();
            $result = new ResultDO();
            $platformType = $platformType ? gdl_lib_BaseUtils::getStr($platformType, 'int') : 0;
            $name = $name ? gdl_lib_BaseUtils::getStr($name) : '';

            if ($platformType == 1) {
                $condition['type'] = $platformType;
                $condition['status'] = 1;
                $items = 'name,real,id';
            } else {
                $leftJoin = array(
                    'agk_user_company as uc' => 'agk_platform.id=uc.platform_id',
                    'agk_user as u' => 'uc.userid=u.userid'
                );
                $condition['agk_platform.type'] = $platformType;
                $condition['agk_platform.status'] = 1;
                $name ? $condition['u.idcard'] = $name : '';
                $items = 'agk_platform.name,agk_platform.real,agk_platform.id';
                $groupBy = 'group by agk_platform.id';
            }
            try {
                $modelPlaform = new model_newagk_platform();
                $res = $modelPlaform->select($condition, $items, $groupBy, '', $leftJoin)->items;

                if ($res) {
                    $result->data = $res;
                    $result->code = 1;
                } else {
                    $result->code = 0;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
        }
    }

    public function getPlaformInfoById($platform_id)
    {
        $platformInfoResultDTO = new PlaformInfoResultDTO();
        $platform_id = gdl_lib_BaseUtils::getStr($platform_id);
        try {
            $modelPlaform = new model_newagk_platform();
            $res = $modelPlaform->selectOne(array("id=$platform_id"), 'id,name,`real`', '', 'order by id desc');
            if ($res) {
                $platformInfoResultDTO->data = $res;
                $platformInfoResultDTO->code = 1;
            } else {
                $platformInfoResultDTO->code = 0;
            }
            $platformInfoResultDTO->success = true;
            return $platformInfoResultDTO;
        } catch (Exception $e) {
            $platformInfoResultDTO->success = false;
            $platformInfoResultDTO->code = $e->getCode();
        }
        return $platformInfoResultDTO;
    }

    public function platformInviteCodeConfirm($code,$userid)
    {
        $platformInviteCodeResultDO = new PlaformInviteCodeResultDTO();
		$platformInviteCodeResultDO->data = [];
		$platformInviteCodeResultDO->success = true;
        $userid = gdl_lib_BaseUtils::getStr($userid, 'int');
        $code = gdl_lib_BaseUtils::getStr($code, 'string');
        try {
            $modelPlaformInviteCode = new model_newagk_platforminvitecode();
            $modelUserCompany = new model_newagk_usercompany();
            $modelPlaform = new model_newagk_platform();
            $res = $modelPlaformInviteCode->selectOne(['code' => $code], 'id,code,platformId,expireTime,status', '', 'order by id desc');
			
            if ($res['id']) {
                if ($this->_time < $res['expireTime'] && $res['status'] == '1') {
                    //开始绑定
					//var_dump($results);exit;
					$modelUcenterMember = new model_agkuc_ucentermember();
					$resUserlist = $modelUcenterMember->selectOne("id='{$userid}'");
					if(!$resUserlist){
						$platformInviteCodeResultDO->code = 400;
                        $platformInviteCodeResultDO->message = '该用户不存在，请传入正确的gdl_userid';
						return $platformInviteCodeResultDO;
					}
					$re = $modelPlaform->getInfoById($res['platformId'], 'admin_reg');
					
					$userModle = new model_newagk_user(); 
					$UserList = $userModle->selectOne(['gdlUserId'=>$resUserlist['id'],'isdelete'=>0],"userId,mobile");
					$userret = $UserList['userId'];
					$idcarinfo = $this->getIdcard($resUserlist['idcard']);
					if(empty($UserList['userId'])){
						# 插入到user
						$userInsert = [
							'gdlUserId' => $resUserlist['id'],
							'userName' => $resUserlist['username'],
							'realName' => $resUserlist['truename'],
							'idcard' => $resUserlist['idcard'],
							'mobile' => $resUserlist['mobile'],
							'createTime'=>time(),
							'admin_reg'=>$re['admin_reg'],
							'isdelete'=>0,
							'status'=>1,
							'birthday'=>$idcarinfo['birth'],
							'sex'=>$idcarinfo['sex'], # 0:男 1 女
							'city'=>"未获取",
							'county'=>"未获取",
							'age'=>$idcarinfo['age'], 
						];
						$userret = $userModle->insert($userInsert);
					}
						
					
                    $results = $modelUserCompany->isUserCompanyExist($userret, $res['platformId']);
                    if (empty($results['id'])) { 
                        $insert = [
                            'userId' => $userret,
							'gdlUserId'=>$userid,
                            'platformId' => $res['platformId'],
                            'admin_reg' => $re['admin_reg'],
							'contactPhone'=>$UserList['mobile'],
							'platformStatus'=>0, # 用户加入平台审核转台0：待审核 1：通过 2：未通过
							'updateTime'=>time(),
							'isdelete'=>0,
							'status'=>1,
                        ];
                        $ret = $modelUserCompany->insert($insert); 
                    } else {
						if($results['isdelete']==1){
							$upCompanyUser['isdelete'] = 0;
							$ret = $modelUserCompany->update(['userId'=>$userret,'platformId'=>$res['platformId']],$upCompanyUser);
						}else{
							$platformInviteCodeResultDO->code = 400;
							$platformInviteCodeResultDO->message = '您已添加过此平台';
							return $platformInviteCodeResultDO;
						}
                    } 
						if (isset($ret)) { 
							$platformInviteCodeResultDO->code = 200;
							$platformInviteCodeResultDO->invitecode = $res['code'];
							$platformInviteCodeResultDO->data = ['userid'=>$userret,'identity_id'=>$ret];
							$platformInviteCodeResultDO->message = '绑定成功';
						} else {
							$platformInviteCodeResultDO->code = 400;
							$platformInviteCodeResultDO->message = '绑定失败,您已添加过此平台了';
						}
                } else {
                    $platformInviteCodeResultDO->code = 400;
                    $platformInviteCodeResultDO->message = '邀请码已过期';
                }
            } else {
                $platformInviteCodeResultDO->code = 400;
                $platformInviteCodeResultDO->message = '邀请码不存在';
            }
        } catch (Exception $e) {
            $platformInviteCodeResultDO->success = false;
            $platformInviteCodeResultDO->code = $e->getCode();
        }
        return $platformInviteCodeResultDO;
    }
	/**
	* 更具userid 和platformid选择平台
	*/
	public function selectPlaform(PlaformDTO $platform){
		$platformId = $platform->platformid ? gdl_lib_BaseUtils::getStr($platform->platformid, 'int') : 0;
		$userid = $platform->userid ? gdl_lib_BaseUtils::getStr($platform->userid, 'int') : 0;
		
		$result = new ResultDO();
		$result->success = true;
		$result->code = 400;
		$result->message = "选择平台失败";
		$result->data = [];
		if(empty($platformId) || empty($userid)){
			$result->message = "缺少必要参数";
			return $result;
		}
		try{
			$platformModel = new model_newagk_platform();
			$userCompanyModel = new model_newagk_usercompany();
			$userModle = new model_newagk_user();
			$condition = [
				'userId'=>$userid,
				'platformId'=>$platformId,
				'isdelete'=>0,
			];
			$userCompany = $userCompanyModel->selectOne($condition, "id,userId,gdlUserId,status,platformStatus,status,isdelete");
			if($userCompany){
				if($userCompany['status']!=1){
					$result->message = "您已被平台管理员禁用，请联系管理员开启";
					return $result;
				}
				# 二期来做
				//if($userCompany['platform_status'] ==0 || $userCompany['platform_status'] ==2){
					//$result->message = "您还未通过平台管理审核，请联系管理员";
					//return $result;
				//}
				# 查询平台信息
				$platformModel = new model_newagk_platform();
				$platformInfo = $platformModel->selectOne(['id'=>$platformId],'id,reals,adminRealname');
				# 记忆当前选择平台
				$userCompanyModel->update(['userid'=>$userid],['defaultPlaform'=>0]);
				$userCompanyModel->update(['id'=>$userCompany['id']],['defaultPlaform'=>1]);
				$result->message = "选择平台成功";
				$result->code = 200; 
				$result->data[] = ['userid'=>$userCompany['userId'],'gdl_userid'=>$userCompany['gdlUserId'],'identity_id'=>$userCompany['id'],'platform_id'=>$platformId,'platformName'=>$platformInfo['reals']];
			}
		}catch(Exception $ex){
			$result->success = false;
			$result->code = 500;
			$result->message = $ex->getMessage();
		}
		
		return $result;
	}

    public function platformInviteCodeAdd(PlaformInviteCodeAddRequestDTO $inviteCodeAddRequestDO)
    {
        //
    }
	/**
		根据身份证获取信息
	*/
	public function getIdcard($idcard){
		//通过身份证号查询出性别与生日 
		$strleng = strlen($idcard);
		$birth = strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8); 
		$getsex = substr($idcard, (strlen($idcard)==$strleng ? -2 : -1), 1) % 2 ? '1' : '0'; //1为男 2为女
		$births = substr($birth,0,4)."-".substr($birth,4,2)."-".substr($birth,6,2);
		$years = date("Y",time());
		$age = $years-substr($birth,0,4);
		$sex = 0;
		if($getsex==1){
			$sex = 0; //男
		}else{
			$sex = 1; //女
		}
		return ['birth'=>$births, 'sex'=>$sex,'age'=>$age];
	}
}
